<template>
  <div>
    <el-row>
      <el-col :span="17" :offset="1">
        <h2>{{ currentNews.title }}</h2>
        <div class="time">
          {{ whichTime(currentNews.editTime) }}
        </div>
        <el-divider>
          <el-icon><star-filled /></el-icon>
        </el-divider>
        <div v-html="currentNews.content" class="htmlcontent"></div>
      </el-col>
      <el-col :span="4" :offset="1" :pull="1">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span style="font-size: 16px; font-weight: bold">最近新闻</span>
            </div>
          </template>
          <div v-for="item in topNewsList" :key="item._id" class="text item" style="padding: 12px; cursor: pointer" @click="handleChange(item._id)">
            <span>{{ item.title }}</span>
            <div class="bottom">
              <time class="time">{{ whichTime(item.editTime) }}</time>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import axios from 'axios'
import moment from 'moment'
import { onMounted, ref, watchEffect, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { StarFilled } from '@element-plus/icons-vue'
moment.locale('zh-cn')
const route = useRoute()
const router = useRouter()
const currentNews = ref({})
const topNewsList = ref({})
// watchEffect 也是一个帧听器，是一个副作用函数。
// 它会监听引用数据类型的所有属性，不需要具体到某个属性，一旦运行就会立即监听，组件卸载的时候会停止监听。
// 这里监听到route.params.id改变
const stop = watchEffect(async () => {
  if (!route.params.id) return
  // console.log(route.params.id)
  const res1 = await axios.get(`/webapi/news/list/${route.params.id}`)
  const res2 = await axios.get(`/webapi/news/toplist?limit=4`)
  // console.log(res1.data.data[0])
  // console.log(res2.data.data)
  currentNews.value = res1.data.data[0]
  topNewsList.value = res2.data.data
})
onBeforeUnmount(() => {
  // 停止监听
  stop()
})
const whichTime = (time) => {
  return moment(time).format('lll')
}
const handleChange = (id) => {
  // console.log(id)
  router.push(`/news/${id}`)
}
</script>

<style lang="scss" scoped>
.el-row {
  margin-top: 30px;
}
.time {
  font-size: 13px;
  color: gray;
}
::v-deep .htmlcontent {
  img {
    max-width: 100%;
  }
}
</style>
